package com.suse.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.suse.model.vo.UserVo;
import com.suse.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;

/**
 * 这里依赖注入比较特殊
 * 当前类不是直接被 Spring 管理的类，不能直接使用依赖注入
 * 始终记住对象在哪里被创建、在哪里被使用
 */
@Slf4j
@Component
public class LoginInteceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 判断用户是否登录
        UserVo userVo = UserHolder.getUser();
        if (ObjectUtil.isNull(userVo)) {
            // 2. 没有登录，拦截
            response.setStatus(SC_UNAUTHORIZED);
            return false;
        }
        // 3. 已登录，放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 回收资源 防止内存泄露
        UserHolder.removeUser();
    }

}
